package org.example.os.synchronous.producer_comsumer;

import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;

/**
 * IO stream 性能低
 */
public class PipedStreamAchievement {
    private final PipedInputStream pis = new PipedInputStream();
    private final PipedOutputStream pos = new PipedOutputStream();
    private volatile boolean isProducing = true;

    public PipedStreamAchievement() {
        try {
            pis.connect(pos);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public void produce() throws IOException, InterruptedException {
        int value = 0;
        while (isProducing) {
            System.out.println("生产者生产: " + value);
            pos.write(value++);
            Thread.sleep(1000);
        }
        pos.close();
    }

    public void consume() throws IOException, InterruptedException {
        int value;
        while ((value = pis.read()) != -1) {
            System.out.println("消费者消费: " + value);
            Thread.sleep(1000);
        }
        pis.close();
    }

    public void stop() {
        isProducing = false;
    }
}
